package cn.nawang.ebeim.server.thread;

import cn.nawang.ebeim.server.queue.TaskQueue;
import cn.nawang.ebeim.server.task.Task;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * IOTask的消费者
 * Created by GanJc on 2015-11-11 17:39
 */
public class TaskExecutor implements Runnable {

    private static final Logger LOG = LoggerFactory.getLogger(TaskExecutor.class);

    private TaskQueue<Task> taskQueue ;

    @SuppressWarnings("unchecked")
    public TaskExecutor(TaskQueue taskQueue) {
        this.taskQueue = taskQueue;
    }

    public void run() {
        while(true){
            Task task = null ;
            try{
                LOG.info("{},Waiting for task :{}",Thread.currentThread().getName(),taskQueue.size());
                task = taskQueue.take();
                LOG.info("Begin execute task :{}",task);
                task.execute();
            }catch(Exception ex){
                LOG.error("Task error:" + task, ex);
                try {
                    taskQueue.put(task);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
